package xyz.jason.mybatisgenerator.filters;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @ProjectName: mybatis-generator
 * @Package: xyz.jason.mybatisgenerator.filters
 * @ClassName: VerificationCodeFilter
 * @Author: Jason · L
 * @Description: 图片验证码
 * @Date: 2021/4/6 15:10
 * @Version: 1.0
 */
@Component
public class VerificationCodeFilter extends OncePerRequestFilter {

    @Value("${redirect}")
    private String redirect;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        if("/doLogin".equals(request.getRequestURI())){
            String reqCaptcha = request.getParameter("captcha");
            HttpSession session = request.getSession();
            String captcha = (String) session.getAttribute("captcha");
            session.removeAttribute("captcha");
            if(!StringUtils.hasLength(reqCaptcha) || !StringUtils.hasLength(captcha) || !reqCaptcha.equals(captcha)){
                response.sendRedirect(redirect);
                return;
            }
        }
        filterChain.doFilter(request,response);
    }
}
